# coding: utf-8
# auth: xd

from datetime import datetime
import argparse
import subprocess
import httplib2
import json,os
import time
import socket

'''
参照：https://consul.docs.apiary.io/#reference/agent-control/checks/delete-a-key
结合consul做服务健康检查与服务自动更新

直接删除路径(通过删除key来自动更新程序)
curl  --request DELETE http://10.101.0.155:8500/v1/kv/transcode?recurse=true

注册服务
curl -X PUT -d'{"id": "redis-xxx", "name": "transcode", "address": "10.101.0.230", "port": "80", "tags": ["java"],\
    "checks": [{"http": "http://10.101.0.230:80/health", "interval": "5s"}]}' \
    http://10.101.0.155:8500/v1/agent/service/register

删除服务
curl -X PUT http://10.101.0.155:8500/v1/agent/service/deregister/redis-xxx
'''

def usage():
    parser = argparse.ArgumentParser (prog = 'PROG')
    parser.add_argument ('--host', help = "Service ip address")
    parser.add_argument ('--port', type = int, help = "Service port number")
    parser.add_argument ('--name', help = "The name of the service")
    parser.add_argument ('--consul', help = "Consul register server address")
    args = parser.parse_args ()
    return args

# 获取本机ip地址
def getHostIp():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

#注册服务，判断服务健康状况
def registratorService(conn,host,port,serverName,url):
    data = {"id": host,"name": serverName,"address": host,"port": port,
            "tags": ["java","transcode"],"checks": [{"http": "http://"+ host+":"+str(port)+'/health',"interval": "5s"}]
            }
    body = json.dumps(data)
    response, content = conn.request(url, method = 'PUT',body = body)


#检查key是否存在
def checkKey(conn,url):
    response, content =conn.request(url)
    if response.status == 404:
        return True
    return False

#注册key到服务发现
def registratorKey(STATUS,conn,url):
    UPDATETIME = datetime.now().strftime('%Y-%m-%d %X')
    if STATUS:
        MSG = 'SUCCESS: Transcoding service restart completed'
    else:
        MSG = 'FAIL: Please delete the current key and restart the transcoding application again'
    data = {'status': STATUS,'updateTime':UPDATETIME,'msg': MSG}
    body = json.dumps(data)
    response, content =conn.request(url,method = 'PUT',body = body)
    if response.status == 200:
        return True
    return False

#重启本地应用服务
def restartApplacation():
    print("重启docker-compose")
    # COMMAND = 'docker-compose up -d'
    # ret, val = subprocess.getstatusoutput (COMMAND)
    ##兼容python2与python3
    os.chdir('/opt/transcode')
    COMMAND = ['docker-compose','pull']
    subprocess.check_call(COMMAND)
    COMMAND = ['docker-compose','-f','/opt/transcode/docker-compose.yml','up','-d','--force-recreate']
    ret = subprocess.check_call(COMMAND)
    ret = 0
    if ret == 0:
        return True
    return False

if __name__ == "__main__":
    consulHost = '10.101.0.155:8500'
    appName = 'transcode'
    port = 80
    # hostKey = '10.101.0.155'
    hostKey = getHostIp()
    # 自动注册key，用于判断服务是否需要重启
    url = 'http://%s/v1/kv/%s/%s:%s' %(consulHost,appName,hostKey,port)

    # 注册服务url，应用健康检查
    regUrl = 'http://%s/v1/agent/service/register' %(consulHost)
    conn = None
    while True:
        conn = httplib2.Http(timeout = 3)
        ##服务镜像包打包并上传到镜像仓库后，会把注册服务中的key删除掉
        ##通过判断注册服务中是否有key，采取是否重启服务。
        if checkKey(conn,url):
            status = restartApplacation()
            if registratorKey(status,conn,url):
                registratorService(conn, hostKey, port, appName, regUrl)
                print('Transcoding service restart completed')
        # else:
        #     time.sleep(30)
        conn.close()
        time.sleep(30)
